<?php

class FormService extends FServiceBase
{    
    /**
    * Get a Form model given its ID
    * 
    * @param int id Form ID
    * @return FServiceModel
    */
    public function get($params){
        $model = Form::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Form','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        
        $element_child_lookup = array(
            'address' => 5,
            'simple_name' => 1,
            'name' => 3
        );

        $form_object        = json_decode($params['form']);
        //CVarDumper::dump($form_object,10,true);Yii::app()->end();
        $elements_object    = json_decode($params['elements']); 
        
        // save form
        if ($form_object->id > 0) {
            $form = Form::model()->findByPk($form_object->id);
            $oldTalbeName = $form->table_name;
            list($form_object->module,,) = explode('.', $form->contentType->model);
            $form_object->content_type_name = $form->contentType->name;
//            $form_object->content_type_desc = $form->contentType->description;
        } else {
            // check for existing table name 
            $tables = Yii::app()->db->Schema->TableNames;
            $form_object->table_name = SITE_TABLE_PREFIX.$form_object->table_name;
            if (array_search($form_object->table_name, $tables) !== false)
                die('{ "status" : "error", "message" : "This form\'s data is saved into the underlying database as a data table. Unfortunately there is already a table with the name we chose. Please help to specify a different name." }'); 
            // ok to create form
            $form = new Form();
            $sql = 'CREATE TABLE "public"."_TABLE_" (
                    "id" serial NOT NULL,
                    PRIMARY KEY ("id")
                    )
                    WITH (OIDS=FALSE)
                    ;';
        }
        
        $form->name             = $form_object->name;
        $form->table_name       = $form_object->table_name;
        $form->description      = $form_object->description;
        $form->redirect         = $form_object->redirect;
        $form->success_message  = $form_object->success_message;
//        $form->password         = $form_object->password;
/*        $form->unique_ip        = $form_object->unique_ip;*/
        $form->permission          = $form_object->permission;
        $form->captcha          = $form_object->captcha;
        if (isset($form_object->log))
            $form->log              = $form_object->log;
        $form->email            = $form_object->email;
        $form->status           = 1;
        $form->creation_datetime= date('Y/m/d'); //time();
        $form->last_update      = date('Y/m/d'); //time();
        
        $form->save();
        $this->result->processed('form_id', $form->id);
        
        // create table if the form was new
        if (isset($sql)) {
            $sql = str_replace('_TABLE_',$form->table_name,$sql);
            Yii::app()->db->createCommand($sql)->execute();
        }
        
        // rename table if talbe_name is changed
        if (isset($oldTalbeName) && $oldTalbeName != $form->table_name) {
            $sql = 'ALTER TABLE "public"."'.$oldTalbeName.'" RENAME TO "'.$form->table_name.'";';
            Yii::app()->db->createCommand($sql)->execute();
        }
        
        // save elements
        $elements_array = $elements_object->elements;
        
        //separate optionable elements (checkbox/radio button/dropdown) from other elements
        $optionable_elements = array();
        $non_optionable_elements = array();
        $aliasElm = false;
        $hasAlias = false;
        foreach ($elements_array as $key=>$value){
            if(($value->type == 'radio') || ($value->type == 'checkbox') || ($value->type == 'select')){
                $optionable_elements[] = $value;
            }else{
                $value->options = null; //remove options for elements other than checkbox/radio/dropdown 
                $non_optionable_elements[] = $value;
            }
            if (isset($oldTalbeName) === false && $aliasElm === false && in_array(strtolower($value->title), array('title', 'name')))
            {
                $aliasElm = clone $value;
                $aliasElm->options = null;
                $aliasElm->title = 'Alias';
                $aliasElm->column_name = 'alias';
            }
            if (strtolower($value->title) == 'alias')
            {
                $hasAlias = true;
            }
        }
        if (is_object($aliasElm) && $hasAlias === false)
            $non_optionable_elements[] = $aliasElm;
        
        //1. Process non optionable elements
        if(!empty($non_optionable_elements)){
            foreach ($non_optionable_elements as $element){
                if(empty($element->is_db_live)){
                    $new_non_optionable_elements[] = $element;
                }else{
                    $old_non_optionable_elements[] = $element;
                }
            }
        }
        //1.1 Process new non-optionable element. Insert to table
        
        if(!empty($new_non_optionable_elements)){
            foreach ($new_non_optionable_elements as $element){
                $elm = new FormElement();
                $elm->form_id = $form->id;
                $this->setElementAttributes($elm, $element);
                
                if(empty($element_child_lookup[$element->type])){
                    $elm->total_child = 0;
                }else{
                    $elm->total_child = $element_child_lookup[$element->type];
                }
                
                if ($elm->type == 'file')
                {
                    $elm->size = $element->file_limit;
                    $elm->default_value = $element->file_ext;
                }
                $elm->save();
                $this->addColumn($form->table_name, $elm->column_name, $element->type, !empty($element->lookup_type),(boolean) $element->is_required);
            }
        }
        
        //add properties table
        if ($form_object->id <= 0)
        {
            $this->addColumn($form->table_name, 'status', 'int2');
            $this->addColumn($form->table_name, 'creation_datetime', 'timestamp');
            $this->addColumn($form->table_name, 'last_update', 'timestamp');
            $this->addColumn($form->table_name, 'created_by', 'int8');
            $this->addColumn($form->table_name, 'updated_by', 'int8');
            
            //update taxonomy term properties
            if (isset($_GET['module'], $_GET['type']))
            {
                $this->addColumn($form->table_name, 'term_id', 'int8');
            }
        }
        
        //1.2 Process old non-optionable element. Update table
        $updatable_element_type = array('phone','simple_phone','date','europe_date');
            
        if(!empty($old_non_optionable_elements)){
            foreach ($old_non_optionable_elements as $element){
                $elm = FormElement::model()->findByPk($element->id);
                // save old column name in case it's changed
                $oldColumnName = $elm->column_name;
                
                $this->setElementAttributes($elm, $element);
                
                if(empty($element_child_lookup[$element->type])){
                    $elm->total_child = 0;
                }else{
                    $elm->total_child = $element_child_lookup[$element->type];
                }
                
//                //special for phone,simple_phone,date,europe_date .. type can be changed
//                if(in_array($element->type,$updatable_element_type)){
//                    $elm->type = $element->type;
//                }else{
//                    unset($element_input['element_type']);
//                } 
                
                if ($elm->type == 'file')
                {
                    $elm->size = $element->file_limit;
                    $elm->default_value = $element->file_ext;
                }
                $elm->save();
                if ($oldColumnName != $elm->column_name)
                    $this->renameColumn($form->table_name, $elm->column_name, $oldColumnName, $elm->type);
            }
        }
        
        //2. Process optionable elements (checkbox/radio button/dropdown)
        foreach ($optionable_elements as $element){
            if(empty($element->is_db_live)){
                $new_optionable_elements[] = $element;
            }else{
                $old_optionable_elements[] = $element;
            }
        }
        
        //2.1 Process new optionable element. Insert to table
        if(!empty($new_optionable_elements)){
            foreach ($new_optionable_elements as $element){
                $elm = new FormElement();
                $elm->form_id = $form->id;
                $this->setElementAttributes($elm, $element);
                
                if(empty($element_child_lookup[$element->type])){
                    $elm->total_child = 0;
                }else{
                    $elm->total_child = $element_child_lookup[$element->type];
                }
                
                if ($elm->type == 'file')
                {
                    $elm->size = $element->file_limit;
                    $elm->default_value = $element->file_ext;
                }
                $elm->save();
                                
//                if(($element->type == 'radio') || ($element->type == 'select')){ //radio button and select only need one field total,,while checkboxes need one field per option
                    $this->addColumn($form->table_name, $elm->column_name, $element->type);
//                }
                
                //insert options into ap_element_options table
                /*$position = 1;
                foreach ($element->options as $option){
                    $option->option = trim($option->option);
                    if(empty($option->option) && ($option->option != '0')){
                        continue;
                    }
                    
                    $elmOpt = new FormElementOption();
                    
                    $elmOpt->form_id               = $elm->form_id;
                    $elmOpt->element_id            = $elm->id;
                    $elmOpt->option                = $option->option;
                    $elmOpt->option_is_default     = $option->is_default;
                    $elmOpt->position              = $position;

                    $elmOpt->save();
                                        
//                    if($element->type == 'checkbox'){
//                        $this->addColumn($form->table_name, $elm->column_name, $element->type, $position);
//                    }
//                    
                    $position++;
                }*/
                
                //update 'element_total_child' on ap_form_elements
//                $position -= 2;
//                do_query("update ap_form_elements set element_total_child='$position' where form_id='$form_id' and element_id='$next_element_id'");
                
            }
        }
        
        //2.2 Process old optionable element. Update table
        if(!empty($old_optionable_elements)){
            foreach ($old_optionable_elements as $element){
                $elm = FormElement::model()->findByPk($element->id);
                $oldColumnName = $elm->column_name;
                
                $this->setElementAttributes($elm, $element);
                
                if(empty($element_child_lookup[$element->type])){
                    $elm->total_child = 0;
                }else{
                    $elm->total_child = $element_child_lookup[$element->type];
                }
                
                if ($elm->type == 'file')
                {
                    $elm->size = $element->file_limit;
                    $elm->default_value = $element->file_ext;
                }
                $elm->save();
//                if ($elm->type != 'checkbox' && $oldColumnName != $elm->column_name)
                if ($oldColumnName != $elm->column_name)
                    $this->renameColumn($form->table_name, $elm->column_name, $oldColumnName, $elm->type);
                
                //update ap_element_options table (checkbox/radio button/dropdown)
                //'erase' all old data
//                $query = "update `ap_element_options` set `live`=0 where form_id='{$form_id}' and element_id='{$element->id}'";
//                
                
                
                //loop through elements
                /*$position = 1;
                foreach ($element->options as $option){
                    $option->option = trim($option->option);
                    if(empty($option->option) && ($option->option != '0')){
                        continue;
                    }
                    $elmOpt = FormElementOption::model()->findByPk($option->id);
                    if (!$elmOpt)
                        $elmOpt = new FormElementOption();
                    
                    $elmOpt->form_id               = $elm->form_id;
                    $elmOpt->element_id            = $elm->id;
                    $elmOpt->option                = $option->option;
                    $elmOpt->option_is_default     = $option->option_is_default;
                    $elmOpt->position              = $position;
                    $elmOpt->live                  = 1;
                    

//                    if(empty($option->id)){ //if id=0 insert new row
//                        if($element->type == 'checkbox'){
//                            $this->addColumn($form->talbe_name, $elm->column_name, $element->type, $position);
//                        }
//                    }elseif ($oldColumnName != $elm->column_name)
//                        $this->renameColumn($form->table_name, $elm->column_name, $oldColumnName, $elm->type, $position);

                    $elmOpt->save();
                    $position++;
                }*/
                
                //update 'element_total_child' on ap_form_elements
//                $position -= 2;
//                do_query("update ap_form_elements set element_total_child='$position' where form_id='$form_id' and element_id='{$element->id}'");
            }
        }
        
        //generate model class
        $this->generateModel($form->table_name, $form, $form_object->module, $form_object->content_type_name);
        
        return $this->result;
    }
    
    protected function setElementAttributes(&$elm, $element) {
        $elm->title         = $element->title;
        $elm->guidelines    = $element->guidelines;
        $elm->size          = $element->size; 
        $elm->is_required   = $element->is_required; 
        $elm->is_unique     = $element->is_unique;
        $elm->is_private    = $element->is_private; 
        $elm->type          = $element->type;
        $elm->position      = $element->position;
        $elm->default_value = $element->default_value;
        $elm->constraint    = $element->constraint;
        $elm->column_name   = strtolower(toSlug($elm->title,'_'));
        if (property_exists($element, 'lookup_type'))
            $elm->lookup_type   = (string) $element->lookup_type;
        if (property_exists($element, 'lookup_value'))
            $elm->lookup_value  = (string) $element->lookup_value;
    }
    
    /**
    * Add a column into form_xx table
    * 
    * @param mixed $form_id
    * @param mixed $element_name
    * @param mixed $type
    * @param mixed $option_id
    */
    protected function addColumn($tableName,$element_name,$type,$isLookup=false,$isRequired=false) {
        $sql = 'ALTER TABLE "public"."_TABLE_" ';
        $columnName = $element_name;
        $required = $isRequired ? " NOT NULL" : "";
        $query = '';
        
        if(('text' == $type) || ('phone' == $type) || ('simple_phone' == $type) || ('url' == $type) || ('email' == $type) || ('file' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" varchar(255){$required};";
            
        }elseif ('textarea' == $type){
            $query = "ADD COLUMN \"{$columnName}\" text;"; //for MySQL 'mediumtext'
            
        }elseif (('radio' == $type) || ('select' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" int2 DEFAULT 0{$required};";
            
        }elseif ('time' == $type){
            $query = "ADD COLUMN \"{$columnName}\" time{$required};";
            
        }elseif (('date' == $type) || ('europe_date' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" timestamp{$required};";
            
        }elseif ('money' == $type){
            $query = "ADD COLUMN \"{$columnName}\" money{$required};"; //for MySQL numeric(62,2)
            
        }elseif ('number' == $type){
            $query = "ADD COLUMN \"{$columnName}\" numeric{$required};";
            
        }elseif ('simple_name' == $type){
            //add two field, first and last name
            $query = "ADD COLUMN \"{$columnName}_first\" varchar(255), 
                      ADD COLUMN \"{$columnName}_last\" varchar(255);";
            
        }elseif ('name' == $type){
            //add four field, title, first, last, suffix 
            $query = "ADD COLUMN \"{$columnName}_title\"  varchar(255), 
                      ADD COLUMN \"{$columnName}_first\"  varchar(255),
                      ADD COLUMN \"{$columnName}_last\"   varchar(255),
                      ADD COLUMN \"{$columnName}_suffix\" varchar(255);";
            
        }elseif ('address' == $type){
            //add six field
            $query = "ADD COLUMN \"{$columnName}_street\"  varchar(255), 
                      ADD COLUMN \"{$columnName}_line2\"   varchar(255), 
                      ADD COLUMN \"{$columnName}_city\"    varchar(255), 
                      ADD COLUMN \"{$columnName}_state\"   varchar(255), 
                      ADD COLUMN \"{$columnName}_code\"    varchar(255), 
                      ADD COLUMN \"{$columnName}_country\" varchar(255);";
            
        }elseif ('checkbox' == $type){
            $query = "ADD COLUMN \"{$columnName}\" text{$required};";
            
        }elseif (('int2' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" int2{$required};";
            
        }elseif (('int8' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" int8{$required};";
            
        }elseif (('timestamp' == $type)){
            $query = "ADD COLUMN \"{$columnName}\" timestamp{$required};";
            
        }
        if (empty($query) === false)
        {
            $sql = str_replace('_TABLE_',$tableName,$sql).' '.$query;
            Yii::app()->db->createCommand($sql)->execute();
        }
    }
    
    protected function renameColumn($talbeName, $newName, $oldNanme, $type, $option_id = null) {
        $sql = 'ALTER TABLE "public"."_TABLE_" ';
        
        if(('text' == $type) || ('phone' == $type) || ('simple_phone' == $type) || ('url' == $type) || ('email' == $type) || ('file' == $type) ||
            ('textarea' == $type) || ('radio' == $type) || ('checkbox' == $type) || ('time' == $type) || ('date' == $type) || ('money' == $type) || ('number' == $type)
        ){
            $query = "RENAME COLUMN \"{$oldNanme}\" TO \"{$newName}\";";
            
        }elseif ('simple_name' == $type){
            //add two field, first and last name
            $query = "RENAME COLUMN \"{$oldNanme}_first\" TO \"{$newName}_first\", 
                      RENAME COLUMN \"{$oldNanme}_last\" TO \"{$newName}_last\"";
            
        }elseif ('name' == $type){
            //add four field, title, first, last, suffix 
            $query = "RENAME COLUMN \"{$oldNanme}_title\" TO \"{$newName}_title\"  , 
                      RENAME COLUMN \"{$oldNanme}_first\" TO \"{$newName}_first\",
                      RENAME COLUMN \"{$oldNanme}_last\" TO \"{$newName}_last\",
                      RENAME COLUMN \"{$oldNanme}_suffix\" TO \"{$newName}_suffix\"";
            
        }elseif ('address' == $type){
            //add six field
            $query = "RENAME COLUMN \"{$oldNanme}_street\" TO \"{$newName}_street\", 
                      RENAME COLUMN \"{$oldNanme}_line2\" TO \"{$newName}_line2\", 
                      RENAME COLUMN \"{$oldNanme}_city\" TO \"{$newName}_city\", 
                      RENAME COLUMN \"{$oldNanme}_state\" TO \"{$newName}_state\", 
                      RENAME COLUMN \"{$oldNanme}_code\" TO \"{$newName}_code\", 
                      RENAME COLUMN \"{$oldNanme}_country\" TO \"{$newName}_country\";";
            
        }
        
        $sql = str_replace('_TABLE_',$talbeName,$sql).' '.$query;
        Yii::app()->db->createCommand($sql)->execute();                
    }
    
    /**
    * Delete a column from table form_xx
    * 
    * @param $form_id
    * @param $element_id
    */
    public function deleteColumn($params) {
        $form_id = $this->getParam($params, 'form_id',0);
        $element_id = $this->getParam($params, 'element_id',0);
        
        if(empty($form_id) || empty($element_id)){
            die('{ "status" : "error", "message" : "invalid parameter" }');
        } 
        
        //get type of this element
        $elm = FormElement::model()->findByPk($element_id);
        $element_type = $elm->type;
        $columnName = toSlug($elm->title,'_');
        
        $col_prefs = array();
        
        $sql = 'ALTER TABLE "public"."_TABLE_" ';
        //delete actual field on respective table data
        if('address' == $element_type){
            $query = "DROP COLUMN \"{$columnName}_street\",
                      DROP COLUMN \"{$columnName}_line2\", 
                      DROP COLUMN \"{$columnName}_city\", 
                      DROP COLUMN \"{$columnName}_state\", 
                      DROP COLUMN \"{$columnName}_code\", 
                      DROP COLUMN \"{$columnName}_country\";";
            
            
            $col_prefs = array("element_{$element_id}_1","element_{$element_id}_2","element_{$element_id}_3","element_{$element_id}_4","element_{$element_id}_5","element_{$element_id}_6");
        }elseif ('simple_name' == $element_type){
            $query = "DROP COLUMN \"{$columnName}_first\",DROP COLUMN \"{$columnName}_last\";";
            
            
            $col_prefs = array("element_{$element_id}_1","element_{$element_id}_2");
        }elseif ('name' == $element_type){
            $query = "DROP COLUMN \"{$columnName}_title\",
                      DROP COLUMN \"{$columnName}_first\", 
                      DROP COLUMN \"{$columnName}_last\", 
                      DROP COLUMN \"{$columnName}_suffix\";";
            
            
            $col_prefs = array("element_{$element_id}_1","element_{$element_id}_2","element_{$element_id}_3","element_{$element_id}_4");
//        }elseif ('checkbox' == $element_type){
//            $query = "";
//            $i = 1;
//            foreach($elm->options as $opt) {
//                $query .= " DROP COLUMN \"{$columnName}_{$i}\",";                
//                $i++;
//            }
//            $query = rtrim($query,',');
        }elseif ('section' == $element_type){
            //do nothing for section break
        }elseif ('file' == $element_type){
            // todo: delete the files first

            
            $query = "DROP COLUMN \"{$columnName}\";";
            $col_prefs = array("element_{$element_id}");
        }else{
            $query = "DROP COLUMN \"$columnName\";";
            
            
            $col_prefs = array("element_{$element_id}");
        }
        
        
        //delete on table ap_element_options
        //FormElementOption::model()->deleteAll("element_id = :id", array(':id' => $element_id));

        //delete on table ap_form_elements
        $elm->delete();
        
        
//        //delete on table ap_column_preferences
//        if(!empty($col_prefs)){
//            foreach ($col_prefs as $element_name){
//                do_query("delete from `ap_column_preferences` where form_id='{$form_id}' and element_name='{$element_name}'");
//            }
//        }
        
//        //if there is no more elements on the table, we need to clear all default fields (id,date_created,date_updated,ip_address) 
//        $query = "select * from `ap_form_{$form_id}` limit 1";
//        if(mysql_num_fields($result) <= 4){
//            $query = "truncate `ap_form_{$form_id}`";
//                
//        }    
        $form = Form::model()->findByPk($form_id);
        $sql = str_replace('_TABLE_',$form->table_name,$sql).' '.$query;
        Yii::app()->db->createCommand($sql)->execute();        

        echo '{ "status" : "ok", "message" : "ok" }';
        die;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Form','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = Form::model()->findByPk($id);
            try {
                $model->delete();
                //delete form row
                //delete form_element
                //delete form_element_option
                //delete form table
                //delete content context
                // only redirect user to the admin page if it is not an AJAX request
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
    
    public function deleteByContentType($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.Form','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            //delete content context
            ContentContext::model()->deleteAllByAttributes(array('content_type_id'=>$id));
            
            $model = Form::model()->findByAttributes(array('content_id'=>$id));
            if (is_object($model)) {
                
                $tableName = $model->table_name;
                $formId = $model->id;
                //delete form row
                $model->delete();
                
                //drop form table
                $command = $model->getDbConnection()->createCommand();
                $command->dropTable($tableName);
                
                //delete form_element
                $command->reset();
                $command->delete(SITE_TABLE_PREFIX.'form_element', 'form_id=:form_id', array(':form_id'=>$formId));
                
                //delete form_element_option                
                //$command->reset();
                //$command->delete('form_element_option', 'form_id=:form_id', array(':form_id'=>$formId));
            }
        }
        return $this->result;
    }
    
    //File Upload
    function display_file($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }

        //check for populated value (this is being used for edit_entry.php only)
        if(!empty($element->populated_value)){
            $file_option = $element->populated_value['element_'.$element->id]['default_value']; //this should be contain html markup to download or delete current file
        }
                
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description" for="element_{$element->id}">{$element->title} {$span_required}</label>
        <div>
            <input id="element_{$element->id}" name="element_{$element->id}" class="element file" type="file" /> 
        </div>{$file_option} {$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }  
    
    //Phone - Extended
    function display_phone($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        //check default value
        if(!empty($element->default_value)){
            //split into (xxx) xxx - xxxx
            $default_value_1 = substr($element->default_value,0,3);
            $default_value_2 = substr($element->default_value,3,3);
            $default_value_3 = substr($element->default_value,6,4);
        }
        
        if(!empty($element->populated_value['element_'.$element->id.'_1']['default_value']) || 
           !empty($element->populated_value['element_'.$element->id.'_2']['default_value']) ||
           !empty($element->populated_value['element_'.$element->id.'_3']['default_value'])
        ){
            $default_value_1 = '';
            $default_value_2 = '';
            $default_value_3 = '';
            $default_value_1 = $element->populated_value['element_'.$element->id.'_1']['default_value'];
            $default_value_2 = $element->populated_value['element_'.$element->id.'_2']['default_value'];
            $default_value_3 = $element->populated_value['element_'.$element->id.'_3']['default_value'];
        }
        
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text" size="3" maxlength="3" value="{$default_value_1}" type="text" /> -
            <label for="element_{$element->id}_1">(###)</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text" size="3" maxlength="3" value="{$default_value_2}" type="text" /> -
            <label for="element_{$element->id}_2">###</label>
        </span>
        <span>
             <input id="element_{$element->id}_3" name="element_{$element->id}_3" class="element text" size="4" maxlength="4" value="{$default_value_3}" type="text" />
            <label for="element_{$element->id}_3">####</label>
        </span>
        {$guidelines} {$error_message}
        </li>
EOT;
        

        return $element_markup;
    }
    
    //Phone - Simple
    function display_simple_phone($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
                
        //check for populated value
        if(!empty($element->populated_value['element_'.$element->id]['default_value'])){
            $element->default_value = $element->populated_value['element_'.$element->id]['default_value'];
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <div>
            <input id="element_{$element->id}" name="element_{$element->id}" class="element text medium" type="text" maxlength="255" value="{$element->default_value}"/> 
        </div>{$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }
    
    
    
    //Date - Normal
    function display_date($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        $machform_path = '';
        if(!empty($element->machform_path)){
            $machform_path = $element->machform_path;
        }
        
        if (empty($element->populated_value ))
            $element->populated_value = array(
                'element_'.$element->id.'_1' => null,
                'element_'.$element->id.'_2' => null,
                'element_'.$element->id.'_3' => null,
            );
            
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text" size="2" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_1']['default_value']}" type="text" /> /
            <label for="element_{$element->id}_1">{$lang['date_mm']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text" size="2" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_2']['default_value']}" type="text" /> /
            <label for="element_{$element->id}_2">{$lang['date_dd']}</label>
        </span>
        <span>
             <input id="element_{$element->id}_3" name="element_{$element->id}_3" class="element text" size="4" maxlength="4" value="{$element->populated_value['element_'.$element->id.'_3']['default_value']}" type="text" />
            <label for="element_{$element->id}_3">{$lang['date_yyyy']}</label>
        </span>
    
        <span id="calendar_{$element->id}">
            <img id="cal_img_{$element->id}" class="datepicker" src="{$machform_path}images/calendar.gif" alt="Pick a date." />    
        </span>
        <script type="text/javascript">
            Calendar.setup({
            inputField     : "element_{$element->id}_3",
            baseField    : "element_{$element->id}",
            displayArea  : "calendar_{$element->id}",
            button         : "cal_img_{$element->id}",
            ifFormat     : "%B %e, %Y",
            onSelect     : selectDate
            });
        </script>
        {$guidelines} {$error_message}
        </li>
EOT;
    
        return $element_markup;
    }
    
    //Date - Normal
    function display_europe_date($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        $machform_path = '';
        if(!empty($element->machform_path)){
            $machform_path = $element->machform_path;
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text" size="2" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_1']['default_value']}" type="text" /> /
            <label for="element_{$element->id}_1">{$lang['date_dd']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text" size="2" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_2']['default_value']}" type="text" /> /
            <label for="element_{$element->id}_2">{$lang['date_mm']}</label>
        </span>
        <span>
             <input id="element_{$element->id}_3" name="element_{$element->id}_3" class="element text" size="4" maxlength="4" value="{$element->populated_value['element_'.$element->id.'_3']['default_value']}" type="text" />
            <label for="element_{$element->id}_3">{$lang['date_yyyy']}</label>
        </span>
    
        <span id="calendar_{$element->id}">
            <img id="cal_img_{$element->id}" class="datepicker" src="{$machform_path}images/calendar.gif" alt="Pick a date." />    
        </span>
        <script type="text/javascript">
            Calendar.setup({
            inputField     : "element_{$element->id}_3",
            baseField    : "element_{$element->id}",
            displayArea  : "calendar_{$element->id}",
            button         : "cal_img_{$element->id}",
            ifFormat     : "%B %e, %Y",
            onSelect     : selectEuropeDate
            });
        </script>
        {$guidelines} {$error_message}
        </li>
EOT;
    
        return $element_markup;
    }

    //Name - Simple
    function display_simple_name($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        if (empty($element->populated_value ))
            $element->populated_value = array(
                'element_'.$element->id.'_first' => null,
                'element_'.$element->id.'_last' => null,
            );
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_first" name= "element_{$element->id}_first" class="element text" maxlength="255" size="8" value="{$element->populated_value['element_'.$element->id.'_first']['default_value']}" />
            <label>{$lang['name_first']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_last" name= "element_{$element->id}_last" class="element text" maxlength="255" size="14" value="{$element->populated_value['element_'.$element->id.'_last']['default_value']}" />
            <label>{$lang['name_last']}</label>
        </span>{$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }

    //Name 
    function display_name($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text" maxlength="255" size="2" value="{$element->populated_value['element_'.$element->id.'_1']['default_value']}" />
            <label>{$lang['name_title']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text" maxlength="255" size="8" value="{$element->populated_value['element_'.$element->id.'_2']['default_value']}" />
            <label class="tam">{$lang['name_first']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_3" name="element_{$element->id}_3" class="element text" maxlength="255" size="14" value="{$element->populated_value['element_'.$element->id.'_3']['default_value']}" />
            <label class="tam">{$lang['name_last']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_4" name="element_{$element->id}_4" class="element text" maxlength="255" size="3" value="{$element->populated_value['element_'.$element->id.'_4']['default_value']}" />
            <label>{$lang['name_suffix']}</label>
        </span>{$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }
    
    //Time
    function display_time($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        if(!empty($element->populated_value['element_'.$element->id.'_4']['default_value'])){
            if($element->populated_value['element_'.$element->id.'_4']['default_value'] == 'AM'){
                $selected_am = 'selected';
            }else{
                $selected_pm = 'selected';
            }
        }
        
        if($element->constraint == 'show_seconds'){
            $seconds_markup =<<<EOT
        <span>
            <input id="element_{$element->id}_3" name="element_{$element->id}_3" class="element text " size="2" type="text" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_3']['default_value']}" />
            <label>{$lang['time_ss']}</label>
        </span>
EOT;
            $seconds_separator = ':';
        }else{
            $seconds_markup = '';
            $seconds_separator = '';
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text " size="2" type="text" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_1']['default_value']}" /> : 
            <label>{$lang['time_hh']}</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text " size="2" type="text" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_2']['default_value']}" /> {$seconds_separator} 
            <label>{$lang['time_mm']}</label>
        </span>
        {$seconds_markup}
        <span>
            <select class="element select" style="width:4em" id="element_{$element->id}_4" name="element_{$element->id}_4">
                <option value="AM" {$selected_am}>AM</option>
                <option value="PM" {$selected_pm}>PM</option>
            </select>
            <label>AM/PM</label>
        </span>{$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }
    
    
    //Price
    function display_money($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        if($element->constraint != 'yen'){ //for dollar, pound and euro
            if($element->constraint == 'pound'){
                $main_cur  = $lang['price_pound_main'];
                $child_cur = $lang['price_pound_sub'];
                $cur_symbol = '&#163;';
            }elseif ($element->constraint == 'euro'){
                $main_cur  = $lang['price_euro_main'];
                $child_cur = $lang['price_euro_sub'];
                $cur_symbol = '&#8364;';
            }else{ //dollar
                $main_cur  = $lang['price_dollar_main'];
                $child_cur = $lang['price_dollar_sub'];
                $cur_symbol = '$';
            }    
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        <span class="symbol">{$cur_symbol}</span>
        <span>
            <input id="element_{$element->id}_1" name="element_{$element->id}_1" class="element text currency" size="10" value="{$element->populated_value['element_'.$element->id.'_1']['default_value']}" type="text" /> .        
            <label for="element_{$element->id}_1">{$main_cur}</label>
        </span>
        <span>
            <input id="element_{$element->id}_2" name="element_{$element->id}_2" class="element text" size="2" maxlength="2" value="{$element->populated_value['element_'.$element->id.'_2']['default_value']}" type="text" />
            <label for="element_{$element->id}_2">{$child_cur}</label>
        </span>
        {$guidelines} {$error_message}
        </li>
EOT;

        }else{ //for yen, only display one textfield
            $main_cur  = $lang['price_yen'];
            $cur_symbol = '&#165;';
            
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description" for="element_{$element->id}">{$element->title} {$span_required}</label>
        <span class="symbol">{$cur_symbol}</span>
        <span>
            <input id="element_{$element->id}" name="element_{$element->id}" class="element text currency" size="10" value="{$element->populated_value['element_'.$element->id]['default_value']}" type="text" />    
            <label for="element_{$element->id}">{$main_cur}</label>
        </span>
        {$guidelines} {$error_message}
        </li>
EOT;
        
        }



        return $element_markup;
    }
    
    //Section Break
    function display_section($element){
    $element->guidelines = nl2br($element->guidelines);            
$element_markup = <<<EOT
        <li id="li_{$element->id}" class="section_break">
            <h3>{$element->title}</h3>
            <p>{$element->guidelines}</p>
        </li>
EOT;
        
        return $element_markup;
    }
    
    //Number
    function display_number($element){
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
                
        //check for populated value, if exist, use it instead default_value
        if(isset($element->populated_value['element_'.$element->id]['default_value'])){
            $element->default_value = $element->populated_value['element_'.$element->id]['default_value'];
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description" for="element_{$element->id}">{$element->title} {$span_required}</label>
        <div>
            <input id="element_{$element->id}" name="element_{$element->id}" class="element text {$element->size}" type="text" maxlength="255" value="{$element->default_value}" /> 
        </div>{$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }   
    
    //Address
    function display_address($element){
        
        $country[0]['label'] = "Afghanistan";
        $country[1]['label'] = "Albania";
        $country[2]['label'] = "Algeria";
        $country[3]['label'] = "Andorra";
        $country[4]['label'] = "Antigua and Barbuda";
        $country[5]['label'] = "Argentina";
        $country[6]['label'] = "Armenia";
        $country[7]['label'] = "Australia";
        $country[8]['label'] = "Austria";
        $country[9]['label'] = "Azerbaijan";
        $country[10]['label'] = "Bahamas";
        $country[11]['label'] = "Bahrain";
        $country[12]['label'] = "Bangladesh";
        $country[13]['label'] = "Barbados";
        $country[14]['label'] = "Belarus";
        $country[15]['label'] = "Belgium";
        $country[16]['label'] = "Belize";
        $country[17]['label'] = "Benin";
        $country[18]['label'] = "Bhutan";
        $country[19]['label'] = "Bolivia";
        $country[20]['label'] = "Bosnia and Herzegovina";
        $country[21]['label'] = "Botswana";
        $country[22]['label'] = "Brazil";
        $country[23]['label'] = "Brunei";
        $country[24]['label'] = "Bulgaria";
        $country[25]['label'] = "Burkina Faso";
        $country[26]['label'] = "Burundi";
        $country[27]['label'] = "Cambodia";
        $country[28]['label'] = "Cameroon";
        $country[29]['label'] = "Canada";
        $country[30]['label'] = "Cape Verde";
        $country[31]['label'] = "Central African Republic";
        $country[32]['label'] = "Chad";
        $country[33]['label'] = "Chile";
        $country[34]['label'] = "China";
        $country[35]['label'] = "Colombia";
        $country[36]['label'] = "Comoros";
        $country[37]['label'] = "Congo";
        $country[38]['label'] = "Costa Rica";
//        $country[39]['label'] = "C?te d'Ivoire";
        $country[40]['label'] = "Croatia";
        $country[41]['label'] = "Cuba";
        $country[42]['label'] = "Cyprus";
        $country[43]['label'] = "Czech Republic";
        $country[44]['label'] = "Denmark";
        $country[45]['label'] = "Djibouti";
        $country[46]['label'] = "Dominica";
        $country[47]['label'] = "Dominican Republic";
        $country[48]['label'] = "East Timor";
        $country[49]['label'] = "Ecuador";
        $country[50]['label'] = "Egypt";
        $country[51]['label'] = "El Salvador";
        $country[52]['label'] = "Equatorial Guinea";
        $country[53]['label'] = "Eritrea";
        $country[54]['label'] = "Estonia";
        $country[55]['label'] = "Ethiopia";
        $country[56]['label'] = "Fiji";
        $country[57]['label'] = "Finland";
        $country[58]['label'] = "France";
        $country[59]['label'] = "Gabon";
        $country[60]['label'] = "Gambia";
        $country[61]['label'] = "Georgia";
        $country[62]['label'] = "Germany";
        $country[63]['label'] = "Ghana";
        $country[64]['label'] = "Greece";
        $country[65]['label'] = "Grenada";
        $country[66]['label'] = "Guatemala";
        $country[67]['label'] = "Guinea";
        $country[68]['label'] = "Guinea-Bissau";
        $country[69]['label'] = "Guyana";
        $country[70]['label'] = "Haiti";
        $country[71]['label'] = "Honduras";
        $country[72]['label'] = "Hong Kong";
        $country[73]['label'] = "Hungary";
        $country[74]['label'] = "Iceland";
        $country[75]['label'] = "India";
        $country[76]['label'] = "Indonesia";
        $country[77]['label'] = "Iran";
        $country[78]['label'] = "Iraq";
        $country[79]['label'] = "Ireland";
        $country[80]['label'] = "Israel";
        $country[81]['label'] = "Italy";
        $country[82]['label'] = "Jamaica";
        $country[83]['label'] = "Japan";
        $country[84]['label'] = "Jordan";
        $country[85]['label'] = "Kazakhstan";
        $country[86]['label'] = "Kenya";
        $country[87]['label'] = "Kiribati";
        $country[88]['label'] = "North Korea";
        $country[89]['label'] = "South Korea";
        $country[90]['label'] = "Kuwait";
        $country[91]['label'] = "Kyrgyzstan";
        $country[92]['label'] = "Laos";
        $country[93]['label'] = "Latvia";
        $country[94]['label'] = "Lebanon";
        $country[95]['label'] = "Lesotho";
        $country[96]['label'] = "Liberia";
        $country[97]['label'] = "Libya";
        $country[98]['label'] = "Liechtenstein";
        $country[99]['label'] = "Lithuania";
        $country[100]['label'] = "Luxembourg";
        $country[101]['label'] = "Macedonia";
        $country[102]['label'] = "Madagascar";
        $country[103]['label'] = "Malawi";
        $country[104]['label'] = "Malaysia";
        $country[105]['label'] = "Maldives";
        $country[106]['label'] = "Mali";
        $country[107]['label'] = "Malta";
        $country[108]['label'] = "Marshall Islands";
        $country[109]['label'] = "Mauritania";
        $country[110]['label'] = "Mauritius";
        $country[111]['label'] = "Mexico";
        $country[112]['label'] = "Micronesia";
        $country[113]['label'] = "Moldova";
        $country[114]['label'] = "Monaco";
        $country[115]['label'] = "Mongolia";
        $country[116]['label'] = "Montenegro";
        $country[117]['label'] = "Morocco";
        $country[118]['label'] = "Mozambique";
        $country[119]['label'] = "Myanmar";
        $country[120]['label'] = "Namibia";
        $country[121]['label'] = "Nauru";
        $country[122]['label'] = "Nepal";
        $country[123]['label'] = "Netherlands";
        $country[124]['label'] = "New Zealand";
        $country[125]['label'] = "Nicaragua";
        $country[126]['label'] = "Niger";
        $country[127]['label'] = "Nigeria";
        $country[128]['label'] = "Norway";
        $country[129]['label'] = "Oman";
        $country[130]['label'] = "Pakistan";
        $country[131]['label'] = "Palau";
        $country[132]['label'] = "Panama";
        $country[133]['label'] = "Papua New Guinea";
        $country[134]['label'] = "Paraguay";
        $country[135]['label'] = "Peru";
        $country[136]['label'] = "Philippines";
        $country[137]['label'] = "Poland";
        $country[138]['label'] = "Portugal";
        $country[139]['label'] = "Puerto Rico";
        $country[140]['label'] = "Qatar";
        $country[141]['label'] = "Romania";
        $country[142]['label'] = "Russia";
        $country[143]['label'] = "Rwanda";
        $country[144]['label'] = "Saint Kitts and Nevis";
        $country[145]['label'] = "Saint Lucia";
        $country[146]['label'] = "Saint Vincent and the Grenadines";
        $country[147]['label'] = "Samoa";
        $country[148]['label'] = "San Marino";
        $country[149]['label'] = "Sao Tome and Principe";
        $country[150]['label'] = "Saudi Arabia";
        $country[151]['label'] = "Senegal";
        $country[152]['label'] = "Serbia and Montenegro";
        $country[153]['label'] = "Seychelles";
        $country[154]['label'] = "Sierra Leone";
        $country[155]['label'] = "Singapore";
        $country[156]['label'] = "Slovakia";
        $country[157]['label'] = "Slovenia";
        $country[158]['label'] = "Solomon Islands";
        $country[159]['label'] = "Somalia";
        $country[160]['label'] = "South Africa";
        $country[161]['label'] = "Spain";
        $country[162]['label'] = "Sri Lanka";
        $country[163]['label'] = "Sudan";
        $country[164]['label'] = "Suriname";
        $country[165]['label'] = "Swaziland";
        $country[166]['label'] = "Sweden";
        $country[167]['label'] = "Switzerland";
        $country[168]['label'] = "Syria";
        $country[169]['label'] = "Taiwan";
        $country[170]['label'] = "Tajikistan";
        $country[171]['label'] = "Tanzania";
        $country[172]['label'] = "Thailand";
        $country[173]['label'] = "Togo";
        $country[174]['label'] = "Tonga";
        $country[175]['label'] = "Trinidad and Tobago";
        $country[176]['label'] = "Tunisia";
        $country[177]['label'] = "Turkey";
        $country[178]['label'] = "Turkmenistan";
        $country[179]['label'] = "Tuvalu";
        $country[180]['label'] = "Uganda";
        $country[181]['label'] = "Ukraine";
        $country[182]['label'] = "United Arab Emirates";
        $country[183]['label'] = "United Kingdom";
        $country[184]['label'] = "United States";
        $country[185]['label'] = "Uruguay";
        $country[186]['label'] = "Uzbekistan";
        $country[187]['label'] = "Vanuatu";
        $country[188]['label'] = "Vatican City";
        $country[189]['label'] = "Venezuela";
        $country[190]['label'] = "Vietnam";
        $country[191]['label'] = "Yemen";
        $country[192]['label'] = "Zambia";
        $country[193]['label'] = "Zimbabwe";
        
        
        $country[0]['value'] = "Afghanistan";
        $country[1]['value'] = "Albania";
        $country[2]['value'] = "Algeria";
        $country[3]['value'] = "Andorra";
        $country[4]['value'] = "Antigua and Barbuda";
        $country[5]['value'] = "Argentina";
        $country[6]['value'] = "Armenia";
        $country[7]['value'] = "Australia";
        $country[8]['value'] = "Austria";
        $country[9]['value'] = "Azerbaijan";
        $country[10]['value'] = "Bahamas";
        $country[11]['value'] = "Bahrain";
        $country[12]['value'] = "Bangladesh";
        $country[13]['value'] = "Barbados";
        $country[14]['value'] = "Belarus";
        $country[15]['value'] = "Belgium";
        $country[16]['value'] = "Belize";
        $country[17]['value'] = "Benin";
        $country[18]['value'] = "Bhutan";
        $country[19]['value'] = "Bolivia";
        $country[20]['value'] = "Bosnia and Herzegovina";
        $country[21]['value'] = "Botswana";
        $country[22]['value'] = "Brazil";
        $country[23]['value'] = "Brunei";
        $country[24]['value'] = "Bulgaria";
        $country[25]['value'] = "Burkina Faso";
        $country[26]['value'] = "Burundi";
        $country[27]['value'] = "Cambodia";
        $country[28]['value'] = "Cameroon";
        $country[29]['value'] = "Canada";
        $country[30]['value'] = "Cape Verde";
        $country[31]['value'] = "Central African Republic";
        $country[32]['value'] = "Chad";
        $country[33]['value'] = "Chile";
        $country[34]['value'] = "China";
        $country[35]['value'] = "Colombia";
        $country[36]['value'] = "Comoros";
        $country[37]['value'] = "Congo";
        $country[38]['value'] = "Costa Rica";
//        $country[39]['value'] = "C?te d'Ivoire";
        $country[40]['value'] = "Croatia";
        $country[41]['value'] = "Cuba";
        $country[42]['value'] = "Cyprus";
        $country[43]['value'] = "Czech Republic";
        $country[44]['value'] = "Denmark";
        $country[45]['value'] = "Djibouti";
        $country[46]['value'] = "Dominica";
        $country[47]['value'] = "Dominican Republic";
        $country[48]['value'] = "East Timor";
        $country[49]['value'] = "Ecuador";
        $country[50]['value'] = "Egypt";
        $country[51]['value'] = "El Salvador";
        $country[52]['value'] = "Equatorial Guinea";
        $country[53]['value'] = "Eritrea";
        $country[54]['value'] = "Estonia";
        $country[55]['value'] = "Ethiopia";
        $country[56]['value'] = "Fiji";
        $country[57]['value'] = "Finland";
        $country[58]['value'] = "France";
        $country[59]['value'] = "Gabon";
        $country[60]['value'] = "Gambia";
        $country[61]['value'] = "Georgia";
        $country[62]['value'] = "Germany";
        $country[63]['value'] = "Ghana";
        $country[64]['value'] = "Greece";
        $country[65]['value'] = "Grenada";
        $country[66]['value'] = "Guatemala";
        $country[67]['value'] = "Guinea";
        $country[68]['value'] = "Guinea-Bissau";
        $country[69]['value'] = "Guyana";
        $country[70]['value'] = "Haiti";
        $country[71]['value'] = "Honduras";
        $country[72]['value'] = "Hong Kong";
        $country[73]['value'] = "Hungary";
        $country[74]['value'] = "Iceland";
        $country[75]['value'] = "India";
        $country[76]['value'] = "Indonesia";
        $country[77]['value'] = "Iran";
        $country[78]['value'] = "Iraq";
        $country[79]['value'] = "Ireland";
        $country[80]['value'] = "Israel";
        $country[81]['value'] = "Italy";
        $country[82]['value'] = "Jamaica";
        $country[83]['value'] = "Japan";
        $country[84]['value'] = "Jordan";
        $country[85]['value'] = "Kazakhstan";
        $country[86]['value'] = "Kenya";
        $country[87]['value'] = "Kiribati";
        $country[88]['value'] = "North Korea";
        $country[89]['value'] = "South Korea";
        $country[90]['value'] = "Kuwait";
        $country[91]['value'] = "Kyrgyzstan";
        $country[92]['value'] = "Laos";
        $country[93]['value'] = "Latvia";
        $country[94]['value'] = "Lebanon";
        $country[95]['value'] = "Lesotho";
        $country[96]['value'] = "Liberia";
        $country[97]['value'] = "Libya";
        $country[98]['value'] = "Liechtenstein";
        $country[99]['value'] = "Lithuania";
        $country[100]['value'] = "Luxembourg";
        $country[101]['value'] = "Macedonia";
        $country[102]['value'] = "Madagascar";
        $country[103]['value'] = "Malawi";
        $country[104]['value'] = "Malaysia";
        $country[105]['value'] = "Maldives";
        $country[106]['value'] = "Mali";
        $country[107]['value'] = "Malta";
        $country[108]['value'] = "Marshall Islands";
        $country[109]['value'] = "Mauritania";
        $country[110]['value'] = "Mauritius";
        $country[111]['value'] = "Mexico";
        $country[112]['value'] = "Micronesia";
        $country[113]['value'] = "Moldova";
        $country[114]['value'] = "Monaco";
        $country[115]['value'] = "Mongolia";
        $country[116]['value'] = "Montenegro";
        $country[117]['value'] = "Morocco";
        $country[118]['value'] = "Mozambique";
        $country[119]['value'] = "Myanmar";
        $country[120]['value'] = "Namibia";
        $country[121]['value'] = "Nauru";
        $country[122]['value'] = "Nepal";
        $country[123]['value'] = "Netherlands";
        $country[124]['value'] = "New Zealand";
        $country[125]['value'] = "Nicaragua";
        $country[126]['value'] = "Niger";
        $country[127]['value'] = "Nigeria";
        $country[128]['value'] = "Norway";
        $country[129]['value'] = "Oman";
        $country[130]['value'] = "Pakistan";
        $country[131]['value'] = "Palau";
        $country[132]['value'] = "Panama";
        $country[133]['value'] = "Papua New Guinea";
        $country[134]['value'] = "Paraguay";
        $country[135]['value'] = "Peru";
        $country[136]['value'] = "Philippines";
        $country[137]['value'] = "Poland";
        $country[138]['value'] = "Portugal";
        $country[139]['value'] = "Puerto Rico";
        $country[140]['value'] = "Qatar";
        $country[141]['value'] = "Romania";
        $country[142]['value'] = "Russia";
        $country[143]['value'] = "Rwanda";
        $country[144]['value'] = "Saint Kitts and Nevis";
        $country[145]['value'] = "Saint Lucia";
        $country[146]['value'] = "Saint Vincent and the Grenadines";
        $country[147]['value'] = "Samoa";
        $country[148]['value'] = "San Marino";
        $country[149]['value'] = "Sao Tome and Principe";
        $country[150]['value'] = "Saudi Arabia";
        $country[151]['value'] = "Senegal";
        $country[152]['value'] = "Serbia and Montenegro";
        $country[153]['value'] = "Seychelles";
        $country[154]['value'] = "Sierra Leone";
        $country[155]['value'] = "Singapore";
        $country[156]['value'] = "Slovakia";
        $country[157]['value'] = "Slovenia";
        $country[158]['value'] = "Solomon Islands";
        $country[159]['value'] = "Somalia";
        $country[160]['value'] = "South Africa";
        $country[161]['value'] = "Spain";
        $country[162]['value'] = "Sri Lanka";
        $country[163]['value'] = "Sudan";
        $country[164]['value'] = "Suriname";
        $country[165]['value'] = "Swaziland";
        $country[166]['value'] = "Sweden";
        $country[167]['value'] = "Switzerland";
        $country[168]['value'] = "Syria";
        $country[169]['value'] = "Taiwan";
        $country[170]['value'] = "Tajikistan";
        $country[171]['value'] = "Tanzania";
        $country[172]['value'] = "Thailand";
        $country[173]['value'] = "Togo";
        $country[174]['value'] = "Tonga";
        $country[175]['value'] = "Trinidad and Tobago";
        $country[176]['value'] = "Tunisia";
        $country[177]['value'] = "Turkey";
        $country[178]['value'] = "Turkmenistan";
        $country[179]['value'] = "Tuvalu";
        $country[180]['value'] = "Uganda";
        $country[181]['value'] = "Ukraine";
        $country[182]['value'] = "United Arab Emirates";
        $country[183]['value'] = "United Kingdom";
        $country[184]['value'] = "United States";
        $country[185]['value'] = "Uruguay";
        $country[186]['value'] = "Uzbekistan";
        $country[187]['value'] = "Vanuatu";
        $country[188]['value'] = "Vatican City";
        $country[189]['value'] = "Venezuela";
        $country[190]['value'] = "Vietnam";
        $country[191]['value'] = "Yemen";
        $country[192]['value'] = "Zambia";
        $country[193]['value'] = "Zimbabwe";
        
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;
        
        if(!empty($element->is_error)){
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }
        
        //check for required
        if($element->is_required){
            $span_required = "<span id=\"required_{$element->id}\" class=\"required\">*</span>";
        }
        
        //check for guidelines
        if(!empty($element->guidelines)){
            $guidelines = "<p class=\"guidelines\" id=\"guide_{$element->id}\"><small>{$element->guidelines}</small></p>";
        }
        
        
        //create country markup, if no default value, provide a blank option
        if(empty($element->default_value)){
            $country_markup = '<option value="" selected="selected"></option>'."\n";
        }else{
            $country_markup = '';
        }
        
        foreach ($country as $data){
            if($data['value'] == $element->default_value){
                $selected = 'selected="selected"';
            }else{
                $selected = '';
            }
            
            //check for populated value, use it instead of default value
            if(!empty($element->populated_value['element_'.$element->id.'_country']['default_value'])){
                $selected = '';
                if($element->populated_value['element_'.$element->id.'_country']['default_value'] == $data['value']){
                    $selected = 'selected="selected"';
                }
            } else {
                $element->populated_value = array(
                    'element_'.$element->id.'_street' => null,
                    'element_'.$element->id.'_line2' => null,
                    'element_'.$element->id.'_city' => null,
                    'element_'.$element->id.'_state' => null,
                    'element_'.$element->id.'_code' => null,
                    'element_'.$element->id.'_country' => null,
                );
            }
            
            $country_markup .= "<option value=\"{$data['value']}\" {$selected}>{$data['label']}</option>\n";
        }
        
$element_markup = <<<EOT
        <li id="li_{$element->id}" {$error_class}>
        <label class="description">{$element->title} {$span_required}</label>
        
        <div id="li_{$element->id}_div_street">
            <input id="element_{$element->id}_street" name="element_{$element->id}_street" class="element text large" value="{$element->populated_value['element_'.$element->id.'_street']['default_value']}" type="text" />
            <label for="element_{$element->id}_street">address 1</label>
        </div>
    
        <div id="li_{$element->id}_div_line2">
            <input id="element_{$element->id}_line2" name="element_{$element->id}_line2" class="element text large" value="{$element->populated_value['element_'.$element->id.'_line2']['default_value']}" type="text" />
            <label for="element_{$element->id}_line2">address 2</label>
        </div>
    
        <div id="li_{$element->id}_div_city" class="left">
            <input id="element_{$element->id}_city" name="element_{$element->id}_city" class="element text medium" value="{$element->populated_value['element_'.$element->id.'_city']['default_value']}" type="text" />
            <label for="element_{$element->id}_city">city</label>
        </div>
    
        <div id="li_{$element->id}_div_state" class="right">
            <input id="element_{$element->id}_state" name="element_{$element->id}_state" class="element text medium"  value="{$element->populated_value['element_'.$element->id.'_state']['default_value']}" type="text" />
            <label for="element_{$element->id}_state">state</label>
        </div>
    
        <div id="li_{$element->id}_div_code" class="left">
            <input id="element_{$element->id}_code" name="element_{$element->id}_code" class="element text medium" maxlength="15" value="{$element->populated_value['element_'.$element->id.'_code']['default_value']}" type="text" />
            <label for="element_{$element->id}_code">zip/postal code</label>
        </div>
        
        <div id="li_{$element->id}_div_country" class="right">
            <select class="element select medium" id="element_{$element->id}_country" name="element_{$element->id}_country"> 
            {$country_markup}    
            </select>
        <label for="element_{$element->id}_country">country</label>
    </div>&nbsp;{$guidelines} {$error_message}
        </li>
EOT;
        
    
        return $element_markup;
    }
    
    
    //Captcha
    function display_captcha($element){
        
        if(!empty($element->error_message)){
            $error_code = $element->error_message;
        }else{
            $error_code = '';
        }
                    
        //check for error
        $error_class = '';
        $error_message = '';
        $span_required = '';
        $guidelines = '';
        global $lang;        
        
        if(!empty($element->is_error)){
            
            if($element->error_message == 'el-required'){
                $element->error_message = $lang['captcha_required'];
                $error_code = '';    
            }elseif ($element->error_message == 'incorrect-captcha-sol'){
                $element->error_message = $lang['captcha_mismatch'];
            }else{
                $element->error_message = "{$lang['captcha_error']} ({$element->error_message})";
            }
            
            $error_class = 'class="error"';
            $error_message = "<p class=\"error\">{$element->error_message}</p>";
        }

        if(!empty($_SERVER['HTTPS'])){
            $use_ssl = true;
        }else{
            $use_ssl = false;
        }
        
        
        if(USE_INTERNAL_CAPTCHA === true){ //use the internal captcha if enabled
        
            $machform_path = '';
            if(!empty($element->machform_path)){
                $machform_path = $element->machform_path;
            }
            
            $timestamp = time(); //use this as paramater for captcha.php, to prevent caching
            
            $element->title = $lang['captcha_title'];
$captcha_html = <<<EOT
<img id="captcha_image" src="{$machform_path}captcha.php?t={$timestamp}" width="200" height="60" alt="Please refresh your browser to see this image." /><br />
<input id="captcha_response_field" name="captcha_response_field" class="element text small" type="text" /><div id="dummy_captcha_internal"></div>
EOT;
             
        }else{ //otherwise use the reCAPTCHA
            $captcha_html = recaptcha_get_html(RECAPTCHA_PUBLIC_KEY, $error_code,$use_ssl);
    
            if($captcha_html === false){
                $domain = str_replace('www.','',$_SERVER['SERVER_NAME']);
                $captcha_html = "<b>Error!</b> You have enabled CAPTCHA but no API key available. <br /><br />To use CAPTCHA you must get an API key from <a href='".recaptcha_get_signup_url($domain,'MachForm')."'>http://recaptcha.net/api/getkey</a><br /><br />After getting the API key, save them into your <b>config.php</b> file.";
                $error_class = 'class="error"';
            }
        }
        
        
        if(function_exists("form{$element->form_id}_hook_pre_captcha")){
            $custom_precaptcha = call_user_func("form{$element->form_id}_hook_pre_captcha");
        }
                
$element_markup = <<<EOT
        <li id="li_captcha" {$error_class}> {$custom_precaptcha}
        <label class="description" for="captcha_response_field">{$element->title} {$span_required}</label>
        <div>
            {$captcha_html}    
        </div>     
        {$guidelines} {$error_message}
        </li>
EOT;
        
        return $element_markup;
    }
    
    
    //Main function to display a form
    //There are few mode when displaying a form
    //1. New blank form (form populated with default values)
    //2. New form with error (displayed when 1 submitted and having error, form populated with user inputs)
    //3. Edit form (form populated with data from db)
    //4. Edit form with error (displayed when 3 submiteed and having error)
    function displayForm($params){

        $form_id = $this->getParam($params,'form_id',0);
        $populated_values = $this->getParam($params,'populated_values', array());
        $error_elements = $this->getParam($params,'error_elements',array());
        $custom_error = $this->getParam($params,'custom_error','');
        $edit_id = $this->getParam($params,'edit_id',0);
        $embed = $this->getParam($params,'embed',false);
        $button_text = $this->getParam($params,'button_text','Submit');
        
        //if there is custom error, don't show other errors
        if(!empty($custom_error)){
            $error_elements = array();
        }
        
        //get form properties data
        $model = Form::model()->findByPk($form_id);
        $form = toStdObject($model);
        
        if(empty($error_elements)){
            $form->is_error     = 0;
        }else{
            $form->is_error     = 1;
        }
        
//        //if this form has review enabled and user are having $_SESSION['review_id'], then populate the form with that values
//        if(!empty($form->review) && !empty($_SESSION['review_id']) && empty($populated_values)){
//            $populated_values = get_entry_values($form_id,$_SESSION['review_id'],true);
//        }
        
        //get elements data
        $j=0;
        $has_calendar = false; //assume the form doesn't have calendar, so it won't load calendar.js
        
        $element = array();
        foreach($model->elements as $e) {
            //populate elements
            $stdE = toStdObject($e);

            //            $element_id = $row['element_id'];
            
            //lookup element options first
            $element_options = array();
            if(count($e->options)){
                foreach ($e->options as $opt){
                    $element_options[] = toStdObject($opt);
                }
            }
            
        
            
            //this data came from db or form submit
            //being used to display edit form or redisplay form with errors and previous inputs
            //this should be optimized in the future, only pass necessary data, not the whole array            
//            $element[$j]->populated_value = $populated_values;
            
            //if there is file upload type, set form enctype to multipart
            if($e->type == 'file')
                $form_enc_type = 'enctype="multipart/form-data"';
            else 
                $form_enc_type = '';
            
            if(!empty($error_elements[$e->id])){
                $stdE->is_error         = 1;
                $stdE->error_message = $error_elements[$e->id];
            }
            
            
            $stdE->default_value = htmlspecialchars($e->default_value);
            
            
            $stdE->constraint     = $e->constraint;
            if(!empty($element_options)){
                $stdE->options     = $element_options;
            }else{
                $stdE->options     = '';
            }
            
            
//            //check for calendar type
//            if($row['element_type'] == 'date' || $row['element_type'] == 'europe_date'){
//                $has_calendar = true;
//            }
            
            $element[] = $stdE;
        }
        
        
//        //add captcha if enable
//        if(!empty($form->captcha) && (empty($edit_id))){
//            $element[$j] = new stdClass();
//            $element[$j]->type             = 'captcha';
//            $element[$j]->form_id         = $form_id;
//            $element[$j]->is_private    = 0;
//            
//            if(!empty($error_elements['element_captcha'])){
//                $element[$j]->is_error         = 1;
//                $element[$j]->error_message = $error_elements['element_captcha'];
//            }
//        }
        
        //generate html markup for each element
        $all_element_markup = '';
        foreach ($element as $element_data){
//            if($element_data->is_private && empty($_SESSION['logged_in'])){ //don't show private element
//                continue;
//            }

            print_r($element_data);
            $all_element_markup .= call_user_func(array($this, 'display_'.$element_data->type),$element_data);
        }
        
        if(!empty($custom_error)){
            $form->error_message =<<<EOT
            <li id="error_message">
                    <h3 id="error_message_title">{$custom_error}</h3>
            </li>    
EOT;
        }elseif(!empty($error_elements)){
            $form->error_message =<<<EOT
            <li id="error_message">
                    <h3 id="error_message_title">{$lang['error_title']}</h3>
                    <p id="error_message_desc">{$lang['error_desc']}</p>
            </li>    
EOT;
        }else
            $form->error_message = '';
        
        
        //display edit_id if there is any
        if(!empty($edit_id)){
            $edit_markup = "<input type=\"hidden\" name=\"edit_id\" value=\"{$edit_id}\" />\n";
        }else{
            $edit_markup = '';
        }
        
//        if(empty($form->review)){
//            $button_text = $lang['submit_button'];
//        }else{
//            $button_text = $lang['continue_button'];
//        }
        
        //markup for submit button
        $button_markup =<<<EOT
        <li id="li_buttons" class="buttons">
                <input type="hidden" name="form_id" value="{$form->id}" />
                {$edit_markup}
                <input type="hidden" name="submit" value="1" />
                <input id="saveForm" class="button_text" type="submit" name="submit" value="{$button_text}" />
        </li>
EOT;
        
//        //check for specific form css, if any, use it instead
//        if($form->has_css){
//            $css_dir = DATA_DIR."/form_{$form_id}/css/";
//        }
//        
//        if(!empty($form->password) && empty($_SESSION['user_authenticated'])){ //if form require password and password hasn't set yet
//            $show_password_form = true;
//            
//        }elseif (!empty($form->password) && !empty($_SESSION['user_authenticated']) && $_SESSION['user_authenticated'] != $form_id){ //if user authenticated but not for this form
//            $show_password_form = true;
//            
//        }else{ //user authenticated for this form, or no password required
//            $show_password_form = false;
//        }
        
        $ul_class = '';
        $custom_element = '';
        if(empty($form->status)){ //if form is not active, don't show the fields
            $form_desc_div ='';    
            $all_element_markup = '';
            $button_markup = '';
            $ul_class = 'class="password"';
            $custom_element =<<<EOT
            <li>
                <h2>{$lang['form_inactive']}</h2>
            </li>
EOT;
//        }elseif($show_password_form){ //don't show form description if this page is password protected and user not authenticated
//            $form_desc_div ='';    
//            $all_element_markup = '';    
//            $custom_element =<<<EOT
//            <li>
//                <h2>{$lang['form_pass_title']}</h2>
//                <div>
//                <input type="password" value="" class="text" name="password" id="password" />
//                <label for="password" class="desc">{$lang['form_pass_desc']}</label>
//                </div>
//            </li>
//EOT;
//            $ul_class = 'class="password"';
        }else{
            if(!empty($form->name) || !empty($form->description)){
                $form->description = nl2br($form->description);
                $form_desc_div =<<<EOT
        <div class="form_description">
            <h2>{$form->name}</h2>
            <p>{$form->description}</p>
        </div>
EOT;
            }
        }
        
        if($embed){
            $embed_class = 'class="embed"';
        }
        
        if($has_calendar){
            $calendar_js = '<script type="text/javascript" src="js/calendar.js"></script>';
        }else{
            $calendar_js = '';
        }


        $form_markup = <<<EOT
        <h1><a>{$form->name}</a></h1>
        <form id="form_{$form->id}" class="appnitro" {$form_enc_type} method="post" action="#main_body">
            {$form_desc_div}                        
            <ul {$ul_class}>
            {$form->error_message}
            {$all_element_markup}
            {$custom_element}
            {$button_markup}
            </ul>
        </form>    
EOT;

        $this->result->processed('html', $form_markup);
        return $this->result;
        
    }
    
    protected function generateModel($tableName, $form, $module, $contentName)
    {
        $generatorPaths = array('Core.extensions.gii.generators');
        $generators = $this->findGenerators($generatorPaths);
        $modelClass = str_replace(SITE_TABLE_PREFIX, '', $tableName);
        $modelClass = explode('_', $modelClass);
        if (is_array($modelClass) && count($modelClass))
        {
            $modelClass = array_map('ucfirst', $modelClass);
            $modelClass = implode('', $modelClass);
        }
        //$modelClass=Yii::import($codeModel,true);
        $model=new FModelCode;
        $model->templates = $generators['model']['templates'];
        $model->loadStickyAttributes();
        $model->attributes=array(
            'tableName'=>$tableName,
            'modelClass'=>$modelClass,
            'baseClass'=>'CActiveRecord',
            'modelPath'=>$module.'.models',
            'template'=>'formbuilder',
        );
        $model->status=CCodeModel::STATUS_PREVIEW;
        $model->form = $form;
        if($model->validate())
        {
            $model->saveStickyAttributes();
            $model->prepare();
        }
        if($model->files!=array())
        {
            $model->status=$model->save() ? CCodeModel::STATUS_SUCCESS : CCodeModel::STATUS_ERROR;
        }
        if ($model->status === CCodeModel::STATUS_SUCCESS)
        {
            $contentType = ContentType::model()->findByPk($form->content_id);
            if (! is_object($contentType))
            {
                $contentType = new ContentType();
                $contentType->creation_datetime = date('Y-m-d H:i:s');
            }
            $contentType->name = $contentName;
            $contentType->description = '';
            $contentType->model = $module.'.models.'.$modelClass;
            $contentType->criteria = serialize(array());            
            $contentType->last_update = date('Y-m-d H:i:s');
            $modelClass[0]=strtolower($modelClass[0]);
            if ($contentType->save())
            {
                /** @var CActiveRecord */
                $form->content_id = $contentType->id;
                $form->update(array('content_id'));
                //update taxonomy term properties
                if (isset($_GET['module'], $_GET['type']))
                {
                    $criteria = new CDbCriteria();
                    $criteria->compare('alias', $_GET['type']);
                    Vocabulary::model()->updateAll(array('properties_form_id'=>$form->id), $criteria);
                }
                
                $criteria = new CDbCriteria();
                $criteria->compare('content_type_id', $contentType->id);
                $criteria->compare('type', 'edit');
                //update context
                if (ContentContext::model()->exists($criteria) === false)
                {
                    $contentContextEdit = new ContentContext();
                    $contentContextEdit->type = 'edit';
                    $contentContextEdit->route = '/'.$module.'/admin/'.$modelClass.'/update';
                    $contentContextEdit->content_type_id = $contentType->id;
                    $contentContextEdit->creation_datetime = $contentContext->last_update = date('Y-m-d H:i:s');
                    $contentContextEdit->params = serialize(array());
                    $contentContextEdit->is_frontend = false;
                    $contentContextEdit->status = true;
                    $contentContextEdit->is_default = true;
                    if (! $contentContextEdit->save())
                    {
                        Yii::log(CVarDumper::dumpAsString($contentContextEdit), CLogger::LEVEL_ERROR);
                    }
                }
                $criteria = new CDbCriteria();
                $criteria->compare('content_type_id', $contentType->id);
                $criteria->compare('type', 'search');
                if (ContentContext::model()->exists($criteria) === false)
                {
                    $contentContextEdit = new ContentContext();
                    $contentContextEdit->type = 'search';
                    $contentContextEdit->route = $module.'.views.admin.'.$modelClass.'._search';
                    $contentContextEdit->content_type_id = $contentType->id;
                    $contentContextEdit->creation_datetime = $contentContext->last_update = date('Y-m-d H:i:s');
                    $contentContextEdit->params = serialize(array());
                    $contentContextEdit->is_frontend = false;
                    $contentContextEdit->status = true;
                    $contentContextEdit->is_default = true;
                    if (! $contentContextEdit->save())
                    {
                        Yii::log(CVarDumper::dumpAsString($contentContextEdit), CLogger::LEVEL_ERROR);
                    }
                }
            }
            else
            {
                echo CVarDumper::dumpAsString($contentType->getErrors());
                Yii::log(CVarDumper::dumpAsString($contentType->getErrors()), CLogger::LEVEL_ERROR);
            }
            $this->generateCrud($contentType->model, $module.'/admin/'.$modelClass, $form);
        }
    }
    
    protected function generateCrud($modelClass,$controller, $form)
    {
        $generatorPaths = array('Core.extensions.gii.generators');
        $generators = $this->findGenerators($generatorPaths);
        //$modelClass=Yii::import($codeModel,true);
        $model=new FCrudCode;
        $model->templates = $generators['crud']['templates'];
        $model->loadStickyAttributes();
        $model->attributes=array(
            'model'=>$modelClass,
            'controller'=>$controller,
            'baseControllerClass'=>'BackOfficeController',
            'template'=>'formbuilder',
        );
        $model->status=CCodeModel::STATUS_PREVIEW;
        $model->form = $form;
        if($model->validate())
        {
            $model->saveStickyAttributes();
            $model->prepare();
        }
        if($model->files!=array())
        {
            $model->status=$model->save() ? CCodeModel::STATUS_SUCCESS : CCodeModel::STATUS_ERROR;
        }
    }

    /**
     * Finds all available code generators and their code templates.
     */
    protected function findGenerators($generatorPaths)
    {
        static $generators;
        if (! isset($generators))
        {
            $generators=array();
            $n=count($generatorPaths);
            for($i=$n-1;$i>=0;--$i)
            {
                $alias=$generatorPaths[$i];
                $path=Yii::getPathOfAlias($alias);
                if($path===false || !is_dir($path))
                    continue;

                $names=scandir($path);
                foreach($names as $name)
                {
                    if($name[0]!=='.' && is_dir($path.'/'.$name))
                    {
                        $className=ucfirst($name).'Generator';
                        if(is_file("$path/$name/$className.php"))
                        {
                            $generators[$name]=array(
                                'class'=>"$alias.$name.$className",
                            );
                        }

                        if(isset($generators[$name]) && is_dir("$path/$name/templates"))
                        {
                            $templatePath="$path/$name/templates";
                            $dirs=scandir($templatePath);
                            foreach($dirs as $dir)
                            {
                                if($dir[0]!=='.' && is_dir($templatePath.'/'.$dir))
                                    $generators[$name]['templates'][$dir]=strtr($templatePath.'/'.$dir,array('/'=>DIRECTORY_SEPARATOR,'\\'=>DIRECTORY_SEPARATOR));
                            }
                        }
                    }
                }
            }
        }
        return $generators;
    }
}

Yii::import('gii.generators.model.ModelCode');
Yii::import('Core.extensions.gii.generators.crud.CrudCode');
Yii::import('gii.CCodeFile');
class FModelCode extends ModelCode
{
    public $form;
    private $_templates;
    
    /**
     * Returns a list of available code templates (name=>directory).
     * This method simply returns the {@link CCodeGenerator::templates} property value.
     * @return array a list of available code templates (name=>directory).
     */
    public function getTemplates()
    {
        return $this->_templates;
    }
    
    public function setTemplates($templates)
    {
        $this->_templates = $templates;
    }

    /**
     * @param CCodeFile $file whether the code file should be saved
     */
    public function confirmed($file)
    {
        return true;
    }

    public function prepare()
    {
        $this->files=array();
        $templatePath=$this->templatePath;

        if(($pos=strrpos($this->tableName,'.'))!==false)
        {
            $schema=substr($this->tableName,0,$pos);
            $tableName=substr($this->tableName,$pos+1);
        }
        else
        {
            $schema='';
            $tableName=$this->tableName;
        }
        if($tableName[strlen($tableName)-1]==='*')
        {
            $tables=Yii::app()->db->schema->getTables($schema);
            if($this->tablePrefix!='')
            {
                foreach($tables as $i=>$table)
                {
                    if(strpos($table->name,$this->tablePrefix)!==0)
                        unset($tables[$i]);
                }
            }
        }
        else
            $tables=array($this->getTableSchema($this->tableName));

        $this->relations=$this->generateRelations();

        foreach($tables as $table)
        {
            //find lookup columns
            $criteria = new CDbCriteria();
            $criteria->compare('form_id', $this->form->id);
            $criteria->compare('lookup_type', 'lookup');
            $lookupColumns = FormElement::model()->findAll($criteria);
            
            $tableName=$this->removePrefix($table->name);
            $className=$this->generateClassName($table->name);
            $params=array(
                'tableName'=>$schema==='' ? $tableName : $schema.'.'.$tableName,
                'modelClass'=>$className,
                'columns'=>$table->columns,
                'labels'=>$this->generateLabels($table),
                'rules'=>$this->generateRules($table),
                'relations'=>isset($this->relations[$className]) ? $this->relations[$className] : array(),
                'form'=>$this->form,
                'lookupColumns'=>$lookupColumns,
            );
            //ModelBase file
            $this->files[]=new CodeFile(
                Yii::getPathOfAlias($this->modelPath).'/base/'.$className.'Base.php',
                $this->render($templatePath.'/modelbase.php', $params)
            );
            //Model file
            $this->files[]=new CodeFile(
                Yii::getPathOfAlias($this->modelPath).'/'.$className.'.php',
                $this->render($templatePath.'/model.php', $params)
            );
        }
    }
}

class CodeFile extends CCodeFile
{
    /**
     * Saves the code into the file {@link path}.
     */
    public function save()
    {
        $newDirMode = 0777;
        $newFileMode = 0666;
        if($this->content===null)  // a directory
        {
            if(!is_dir($this->path))
            {
                $oldmask=@umask(0);
                $result=@mkdir($this->path,$newDirMode,true);
                @umask($oldmask);
                if(!$result)
                {
                    $this->error="Unable to create the directory '{$this->path}'.";
                    return false;
                }
            }
            return true;
        }

        if($this->operation===self::OP_NEW)
        {
            $dir=dirname($this->path);
            if(!is_dir($dir))
            {
                $oldmask=@umask(0);
                $result=@mkdir($dir,$newDirMode,true);
                @umask($oldmask);
                if(!$result)
                {
                    $this->error="Unable to create the directory '$dir'.";
                    return false;
                }
            }
        }
        if(@file_put_contents($this->path,$this->content)===false)
        {
            $this->error="Unable to write the file '{$this->path}'.";
            return false;
        }
        else
        {
            $oldmask=@umask(0);
            @chmod($this->path,$newFileMode);
            @umask($oldmask);
        }
        return true;
    }
}

class FCrudCode extends CrudCode
{
    public $form;
    public $_templates;
    /**
     * Returns a list of available code templates (name=>directory).
     * This method simply returns the {@link CCodeGenerator::templates} property value.
     * @return array a list of available code templates (name=>directory).
     */
    public function getTemplates()
    {
        return $this->_templates;
    }
    
    public function setTemplates($templates)
    {
        $this->_templates = $templates;
    }

    /**
     * @param CCodeFile $file whether the code file should be saved
     */
    public function confirmed($file)
    {
        return true;
    }
    
    public function prepare()
    {
        $this->files=array();
        $templatePath=$this->templatePath;
        // controller
        $controllerTemplateFile=$templatePath.DIRECTORY_SEPARATOR.'controller.php';

        $this->files[]=new CodeFile(
            $this->controllerFile,
            $this->render($controllerTemplateFile, array('form'=>$this->form))
        );

        // service
        $serviceTemplateFile=$templatePath.DIRECTORY_SEPARATOR.'service.php';

        $this->files[]=new CodeFile(
            $this->Module->BasePath.DIRECTORY_SEPARATOR.'services'.DIRECTORY_SEPARATOR.$this->getModelClass().'Service.php',
            $this->render($serviceTemplateFile, array('form'=>$this->form))
        );

        // views
        $files=scandir($templatePath);
        foreach($files as $file)
        {
            if(is_file($templatePath.'/'.$file) && CFileHelper::getExtension($file)==='php' && $file!=='controller.php' && $file!='service.php')
            {
                $this->files[]=new CodeFile(
                    $this->viewPath.DIRECTORY_SEPARATOR.$file,
                    $this->render($templatePath.'/'.$file, array('form'=>$this->form))
                );
            }
        }
    }
}
